import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterzhuyili/page/gameSelect.dart';
import 'package:flutterzhuyili/page/router.dart';
import 'package:flutterzhuyili/utils/shared_preferences_keys.dart';
import 'package:flutterzhuyili/utils/textMessage.dart';
import 'package:permission_handler/permission_handler.dart';

import '../main.dart';

class SplashPage extends StatefulWidget {
  SplashPage({Key key}) : super(key: key);

  @override
  _SplashPage createState() => new _SplashPage();
}

class _SplashPage extends State<SplashPage> {
  bool isStartHomePage = false;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new GestureDetector(
      onTap: goToHomePage, //设置页面点击事件
      child: Container(
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Image.asset(
            "assets/images/slogan.png",
            fit: BoxFit.none,
          ),
        ),
        color: Color(0xFF2EB2FF),
      ),
    );
  }

  //页面初始化状态的方法
  @override
  void initState() {
    if (!hasShowAD) {
//      loadSplashAd(mCodeId: '887359355', debug: false);
      hasShowAD = true;
    }
    requestPermission();
    super.initState();
    //开启倒计时
//    countDown();
  }

  void countDown() {
    //设置倒计时1秒后执行跳转方法
    var duration = new Duration(seconds: 1);
    new Future.delayed(duration, () {
      goToHomePage();
    });
  }

  void goToHomePage() {
    //如果页面还未跳转过则跳转页面
    if (!isStartHomePage) {
      //跳转主页 且销毁当前页面
      Navigator.of(context).pushAndRemoveUntil(
          new MaterialPageRoute(builder: (context) => new GameSelectPage()),
          (Route<dynamic> rout) => false);
      isStartHomePage = true;
    }
  }

  requestPermission() async {
    // 申请权限
    await PermissionHandler().requestPermissions(
        [PermissionGroup.microphone, PermissionGroup.storage]);

    // 申请结果
    PermissionStatus micPermission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.microphone);
    PermissionStatus storagePermission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.storage);

    if (micPermission == PermissionStatus.granted &&
        storagePermission == PermissionStatus.granted) {
      countDown();
    } else {
      countDown();
    }
  }
}
